package com.helloandroid

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import com.business.Analyse
import com.business.AnalyseKey
import com.cy.game.CyHomeActivity
import com.hby.game.HbyGame
import com.helloandroid.activitys.*
import com.helloandroid.ads.SmallNativeAdUtil
import com.helloandroid.ads.VideoAdUtil
import com.helloandroid.dialogs.AwardDialog
import com.helloandroid.models.ZhuanViewModel
import com.helloandroid.tools.AppConfig
import com.helloandroid.tools.MyLog
import com.helloandroid.tools.NetWorkUtil
import com.helloandroid.vo.*
import com.jf.game.JfGame
import com.zp.game.ZpGame
import dai.ui.*
import dai.ui.composition.Parallel
import dai.ui.single.Delay
import dai.ui.single.RotateTo
import dai.ui.single.ScaleTo


open class TaskAdapter(private val fragment: BaseZhuanFragment) : RecyclerView.Adapter<ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val rootView = LayoutInflater.from(parent.context).inflate(R.layout.dd_item_task, parent, false)
        return ViewHolder(rootView,
                rootView.findViewById(R.id.ivIcon),
                rootView.findViewById(R.id.tvTitle),
                rootView.findViewById(R.id.tvDesc),
                rootView.findViewById(R.id.tvCoin),
                rootView.findViewById(R.id.tvTargetValue),
                rootView.findViewById(R.id.btn)
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = fragment.localDataLst[position]
        holder.ivIcon.setImageResource(item.resIcon)
        holder.tvTitle.text = item.title
        holder.tvDesc.text = item.desc
        holder.tvCoin.text = "+${item.coin}"
        if (item.target > 0) {
            holder.tvTargetValue.visibility = View.VISIBLE
            holder.tvTargetValue.text = "(0/${item.target})"
        } else {
            holder.tvTargetValue.visibility = View.GONE
        }

        val btnState: BtnState

        // 判断是否已经ready
        if (fragment.isReady) {
            // 判断按钮状态
            val taskInfo = fragment.mInfo!!
            btnState = taskInfo.processUI(item.type, holder, item)
        } else {
            holder.btn.text = "去完成"
            holder.btn.setBackgroundResource(R.drawable.btn_blue)
            btnState = BtnState.Unknow
        }

        when (btnState) {
            BtnState.Unknow,
            BtnState.Geted -> holder.btn.setOnClickListener(null)

            // 领取
            BtnState.Getable -> holder.btn.setOnClickListener {
                fragment.getAward(item)
            }

            // 去完成
            BtnState.UnCompleted -> holder.btn.setOnClickListener {
                when (item.type) {
                    Type.Shoucitixian -> {
                        MyLog.info("去首次提现")
                        fragment.jumpTo(TXActivity::class.java)
                    }
                    Type.BuShu -> {
                        MyLog.info("去步数")
                        fragment.switchToZouFragment()
                    }
                    Type.BangdingWX -> {
                        MyLog.info("去绑定微信")
                        fragment.swithToWodeFragment()
                    }
                    Type.Share -> {
                        MyLog.info("去分享")
                        // TODO:
                    }
                    Type.TianTianHongBao -> {
                        MyLog.info("去天天红包赛")
                        fragment.jumpTo(TianTianHongBaoActivity::class.java)
                    }
                    Type.TianTianYunDong -> {
                        MyLog.info("去每日运动")
                        fragment.jumpTo(MeiRiYunDongActivity::class.java)
                    }
                    Type.ViewVideo -> {
                        MyLog.elog("去看视频")
                        VideoAdUtil.playVideoAd(fragment.requireActivity()) { success ->
                            if (success) {
                                fragment.mInfo!!.video.count++
                                fragment.initUI()
                            }else{
                                AppUtil.toast("视频还没准备好!")
                            }
                        }
                    }
                    Type.HeShui -> {
                        MyLog.info("去喝水")
                        fragment.jumpTo(HeShuiDaKaActivity::class.java)
                    }
                    Type.ZhuanPan -> {
                        MyLog.info("去转盘")
                        fragment.jumpTo(ZpGame::class.java)
                    }
                    Type.ChengYu -> {
                        MyLog.info("去成语")
                        fragment.jumpTo(CyHomeActivity::class.java)
                    }
                    Type.HongBaoYu -> {
                        MyLog.info("去红包雨")
                        // 判断是否可以跳转
                        if (AppUtil.isHbyCanPlay()) {
                            fragment.jumpTo(HbyGame::class.java)
                        } else {
                            AppUtil.toast("时间还未到.")
                        }
                    }
                    Type.JiFuZi -> {
                        MyLog.info("去积福")
                        fragment.jumpTo(JfGame::class.java)
                    }
                    Type.ZaoWanDaKa -> {
                        MyLog.info("去早晚打卡")
                        fragment.jumpTo(ZaoWanDaKaActivity::class.java)
                    }
                    Type.ChiFan -> {
                        MyLog.info("去吃饭")
                        fragment.jumpTo(ChiFanActivity::class.java)
                    }
                }
            }
        }
    }

    override fun getItemCount(): Int {
        return fragment.localDataLst.size
    }
}

class ZhuanzhuanFragment : BaseZhuanFragment() {

    val model: ZhuanViewModel by viewModels()
    val tweenModel: UITweenModel by viewModels()

    private lateinit var adapter: TaskAdapter
    private lateinit var iv1: ImageView
    private lateinit var iv2: ImageView
    private lateinit var iv3: ImageView
    private lateinit var iv4: ImageView
    private lateinit var iv5: ImageView
    private lateinit var iv6: ImageView
    private lateinit var iv7: ImageView
    private lateinit var tv1: TextView
    private lateinit var tv2: TextView
    private lateinit var tv3: TextView
    private lateinit var tv4: TextView
    private lateinit var tv5: TextView
    private lateinit var tv6: TextView
    private lateinit var tv7: TextView
    lateinit var tvSignInfo: TextView

    var runningTween: UITween? = null

    override fun getLayoutResId() = R.layout.fragment_zhuanzhuan

    override fun initView(view: View) {

        localDataLst.clear()
        localDataLst.addAll(dataLst)

        tweenModel.startLoop()

        // init listview
        val rvTask = findViewById<RecyclerView>(R.id.rvTask)
        adapter = TaskAdapter(this)
        rvTask.adapter = adapter

        // init sign
        iv1 = findViewById(R.id.iv_1)
        iv2 = findViewById(R.id.iv_2)
        iv3 = findViewById(R.id.iv_3)
        iv4 = findViewById(R.id.iv_4)
        iv5 = findViewById(R.id.iv_5)
        iv6 = findViewById(R.id.iv_6)
        iv7 = findViewById(R.id.iv_7)
        tv1 = findViewById(R.id.tv_1)
        tv2 = findViewById(R.id.tv_2)
        tv3 = findViewById(R.id.tv_3)
        tv4 = findViewById(R.id.tv_4)
        tv5 = findViewById(R.id.tv_5)
        tv6 = findViewById(R.id.tv_6)
        tv7 = findViewById(R.id.tv_7)
        //shSign = findViewById(R.id.shSign)
        tvSignInfo = findViewById(R.id.tvSignInfo)
        initSignUI()

        //
        if (AppUtil.serverConfig.zzPageNativeAds > 0){
            SmallNativeAdUtil.showNativeAd(requireActivity(), findViewById(R.id.nativeView))
        }
    }

    override fun initData() {
        model.getInfo { success, info ->
            isReady = success
            if (isReady) {
                mInfo = info
                initUI()
            }
        }
    }

    private fun initSignUI() {
        tvSignInfo.text = "已经签到${AppUtil.user.signed_count}天"

        // 签到,判断今天是第几天
        val idx = AppUtil.user.signed_count % 7
        val lstImageView = listOf(iv1, iv2, iv3, iv4, iv5, iv6, iv7)
        val lstTextView = listOf(tv1, tv2, tv3, tv4, tv5, tv6, tv7)
        MyLog.elog("idx:$idx")
        if (AppUtil.canSign()) {
            MyLog.elog("可以签到....")
            // 判断第几个
            // [0,idx) 显示成已签到状态
            // idx 为可以签到
            // (idx,6] 显示为还未到 签到时间
            for (i in 0..6) {
                when {
                    i < idx -> showAlreadySign(lstImageView[i], lstTextView[i])
                    i == idx -> with(lstImageView[i]) {
                        playShakeAnim(this)
                        lstTextView[i].text = "可签到"
                        setImageResource(R.drawable.dd_qiandao_logo1)
                        setOnClickListener {
                            sign()
                        }
                    }
                    else -> showTimeNotYetSign(i, lstImageView[i], lstTextView[i])
                }
            }
        } else {
            MyLog.elog("不可以签到....")
            // 今天已经签到
            // [0,idx) 显示成已经签到
            // [idx,6] 显示为还未到 签到时间
            for (i in 0..6) {
                when {
                    i < idx -> showAlreadySign(lstImageView[i], lstTextView[i])
                    else -> showTimeNotYetSign(i, lstImageView[i], lstTextView[i])
                }
            }
        }
    }

    private fun playShakeAnim(v: View) {
        MyLog.info("=========playShakeAnim called!")

        val tween1 = ScaleTo(0.25f, 0.8f, 0.8f)
                .scaleTo(0.25f, 1f, 1f)
                .delay(0.5f)

        val tween2 = RotateTo(0.1f, -5f)
                .rotateTo(0.1f, -5f)
                .rotateTo(0.1f, 5f)
                .rotateTo(0.1f, -5f)
                .rotateTo(0.1f, 5f)
                .rotateTo(0.1f, -5f)
                .rotateTo(0.1f, 5f)
                .rotateTo(0.1f, -5f)
                .rotateTo(0.1f, 5f)
                .rotateTo(0.1f, -5f)
                .rotateTo(0.1f, 5f)
                .rotateTo(0.1f, 0f)

        runningTween = Delay(0.2f)
                .repeat(-1, Parallel(tween1, tween2))
                .runBy(v, tweenModel)
    }

    private fun showTimeNotYetSign(idx: Int, imageView: ImageView, textView: TextView) {
        textView.text = "第${idx + 1}天"
        with(imageView) {
            setImageResource(R.drawable.dd_qiandao_logo3)
            setOnClickListener {
                AppUtil.toast("还没到签到时间!")
            }
        }
    }

    private fun showAlreadySign(imageView: ImageView, textView: TextView) {
        textView.text = "已签到"
        with(imageView) {
            setImageResource(R.drawable.dd_qiandao_logo2)
            setOnClickListener {
                AppUtil.toast("已经签到!")
            }
        }
    }

     override fun initUI() {
        adapter.notifyDataSetChanged()
    }

    override fun switchToZouFragment() {
        val mainActivity = requireActivity() as MainActivity
        mainActivity.swithToZouFragment()
    }

    override fun swithToWodeFragment() {
        val mainActivity = requireActivity() as MainActivity
        mainActivity.swithToWodeFragment()
    }

    private fun sign() {
        if (!NetWorkUtil.networkConnected()) {
            AppUtil.toast("请打开网络!")
            return
        }

        if (AppUtil.serverConfig.dailySignVideo > 0){
            VideoAdUtil.playVideoAd(requireActivity()){success->
                if (success){
                    realSign()
                }else{
                    AppUtil.toast("视频还未准备好!")
                }
            }
        }else{
            realSign()
        }
    }

    private fun realSign(){
        Analyse.report(AnalyseKey.SignAward)

        // 直接给奖励
        val user = AppUtil.user
        var awardCoin = AppConfig.getSignAwardCount(user.signed_count)
        AppUtil.appViewModel().zhuanSign(awardCoin)

        // 更新UI
        AppUtil.updateSignInfo(AppUtil.sysTime, user.signed_count + 1)
        initSignUI()

        // 显示弹窗
        val dialog = AwardDialog(this, awardCoin)
        dialog.reasonKey = AnalyseKey.Sign_Video
        dialog.show()

        // 停掉动画
        runningTween?.let {
            val view = it.headTween.target
            if (view != null) {
                tweenModel.tweenManager.removeTweenByNode(view)
                view.rotation = 0f
                view.scaleX = 1f
                view.scaleY = 1f
            }
        }
    }
}